package com.guoyw.seata.order.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.guoyw.seata.order.entity.TOrder;
import com.guoyw.seata.order.mapper.TOrderMapper;
import com.guoyw.seata.order.service.ITOrderService;
import com.guoyw.seata.common.dto.AccountDTO;
import com.guoyw.seata.common.dto.OrderDTO;
import com.guoyw.seata.common.dubbo.AccountDubboService;
import com.guoyw.seata.common.enums.RspStatusEnum;
import com.guoyw.seata.common.response.ObjectResponse;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;

import java.util.UUID;

/**
 * author: guoyw
 * create: 2020-09-19 16:42
 **/

@Service
public class ITOrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder> implements ITOrderService{
  
  @Reference(version = "1.0.0")
  private AccountDubboService accountDubboService;
  
  /**
   * 创建订单
   * @Param:  OrderDTO  订单对象
   * @Return:  OrderDTO  订单对象
   */
  @Override
  public ObjectResponse<OrderDTO> createOrder(OrderDTO orderDTO){
    ObjectResponse<OrderDTO> response = new ObjectResponse<>();
    //扣减用户账户
    AccountDTO accountDTO = new AccountDTO();
    accountDTO.setUserId(orderDTO.getUserId());
    accountDTO.setAmount(orderDTO.getOrderAmount());
    ObjectResponse objectResponse = accountDubboService.decreaseAccount(accountDTO);
  
    //生成订单号
    orderDTO.setOrderNo(UUID.randomUUID().toString().replace("-",""));
    //生成订单
    TOrder tOrder = new TOrder();
    BeanUtils.copyProperties(orderDTO,tOrder);
    tOrder.setCount(orderDTO.getOrderCount());
    tOrder.setAmount(orderDTO.getOrderAmount().doubleValue());
    try {
      baseMapper.createOrder(tOrder);
    } catch (Exception e) {
      response.setStatus(RspStatusEnum.FAIL.getCode());
      response.setMessage(RspStatusEnum.FAIL.getMessage());
      return response;
    }
  
    if (objectResponse.getStatus() != 200) {
      response.setStatus(RspStatusEnum.FAIL.getCode());
      response.setMessage(RspStatusEnum.FAIL.getMessage());
      return response;
    }
  
    response.setStatus(RspStatusEnum.SUCCESS.getCode());
    response.setMessage(RspStatusEnum.SUCCESS.getMessage());
    return response;
  }
}
